<template>
  <Form ref="formCom" :validation-schema="mySchema" v-slot="{errors}" autocomplete="off" class="xtx-form">
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-user"></i>
        <!-- <input class="input" type="text" placeholder="请输入用户名" /> -->
        <Field name="account" v-model="form.account" :class="{err: errors.account}" class="input" type="text" placeholder="请输入用户名"/>
      </div>
      <div class="error" v-if="errors.account"> {{ errors.account }} </div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <!-- <input class="input" type="text" placeholder="请输入手机号" /> -->
        <Field name="mobile" v-model="form.mobile" :class="{err: errors.mobile}" class="input" type="number" placeholder="请输入手机号"/>
      </div>
      <div class="error" v-if="errors.mobile"> {{ errors.mobile }} </div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <!-- <input class="input" type="text" placeholder="请输入验证码" /> -->
        <Field name="code" v-model="form.code" :class="{err: errors.code}" class="input" type="text" placeholder="请输入验证码"/>
        <span class="code" @click="send">
          {{ countTime === 0 ? '发送验证码' : countTime + 's' }}
        </span>
      </div>
      <div class="error" v-if="errors.code"> {{ errors.code }} </div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <!-- <input class="input" type="password" placeholder="请输入密码" /> -->
        <Field name="password" v-model="form.password" :class="{err: errors.password}" class="input" type="password" placeholder="请输入密码"/>
      </div>
      <div class="error" v-if="errors.password"> {{ errors.password }} </div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <!-- <input class="input" type="password" placeholder="请确认密码" /> -->
        <Field name="rePassword" v-model="form.rePassword" :class="{err: errors.rePassword}" class="input" type="password" placeholder="请确认密码"/>
      </div>
      <div class="error" v-if="errors.rePassword"> {{ errors.rePassword }} </div>
    </div>
    <a href="javascript:;" class="submit" @click="submit">立即提交</a>
  </Form>
</template>

<script>
import { Form, Field } from 'vee-validate'
import schema from '@/utils/validate-schema'
import { reactive, ref } from 'vue'
import { userQQPatchCode, userQQPatchLogin } from '@/api/user'
import { useCountDown } from '@/compositions/index'
import { message } from '@/components/Message/index.js'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackPatch',
  components: {
    Form,
    Field
  },
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    // 表单数据对象
    const form = reactive({
      account: null,
      mobile: null,
      code: null,
      password: null,
      rePassword: null
    })
    // 表单校验规则
    const mySchema = {
      account: schema.account,
      mobile: schema.mobile,
      code: schema.code,
      password: schema.password,
      rePassword: schema.rePassword
    }

    // --------------------------- 发送验证码
    const { countTime, start } = useCountDown(60)
    const formCom = ref(null)
    // 1. 发送验证码
    // 1.1 绑定发送验证码按钮点击事件
    // 1.2 校验手机号，如果成功才去发送短信（定义API），请求成功开启60s的倒计时，不能再次点击，倒计时结束恢复
    // 1.3 如果失败，失败的校验样式显示出来
    function send () {
      const valid = mySchema.mobile(form.mobile)
      if (valid === true) { // 手机号校验通过
        if (countTime.value === 0) { // 没有倒计时才调用接口
          userQQPatchCode(form.mobile).then(res => {
            console.log('获取验证码结果', res)
            message({ type: 'success', text: '发送成功' })
            start() // 开启倒计时
          }).catch(err => { // 报错 400，想获取到后台返回的错误信息而不是axios给出的错误信息，需要自己判断状态码400的时候，手动抛出后台的提示信息
            console.log('err', err.data.message)
            message({ type: 'error', text: err.data.message })
          })
        }
      } else {
        // 失败，使用vee的错误函数显示错误信息 setFieldError(字段,错误信息)
        formCom.value.setFieldError('mobile', valid) // mobile框的提示信息
      }
    }

    // --------------------- 绑定业务实现
    // 点击 提交按钮 实现绑定逻辑 完善用户信息
    const store = useStore()
    const router = useRouter()
    async function submit () {
      // 表单兜底校验
      const valid = await formCom.value.validate()
      if (valid) { // 通过兜底校验
        userQQPatchLogin({ unionId: props.unionId, ...form }).then(res => {
          console.log('完善资料结果', res)
          // 实现和之前登录一样的逻辑
          store.commit('user/setUser', res.result)
          // 触发action函数进行购物车合并
          store.dispatch('cart/mergeCartList')
          // 跳转到来源也或者首页
          router.push('/')
        }).catch(e => {
          message({ type: 'error', text: '完善信息失败' })
        })
      }
    }

    return { form, mySchema, send, countTime, start, submit, formCom }
  }
}
</script>

<style scoped lang='less'>
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
